package org.wisteria.socket.netty4.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wisteria.socket.SocketServer;

public class Netty4SocketServer implements SocketServer {

    private static final Logger logger = LoggerFactory.getLogger(Netty4SocketServer.class);

    private static final int DEFAULT_PORT = 8080;

    @Override
    public void start() {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new ServerChannelHandler());
                    }
                });


        bind(serverBootstrap, DEFAULT_PORT);
    }

    private void bind(ServerBootstrap bootstrap, int port) {
        bootstrap.bind(port).addListener(future -> {
           if (future.isSuccess()) {
               logger.debug("Netty server started. Port: " + port);
           } else {
               logger.error("Netty server start failed. Port: " + port);
           }
        });
    }
}
